﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using System.Net.Http.Formatting;
using MxTol.API.Helpers;
using MxTol.Managers;

namespace MxTol.API.Controllers
{
    /// <summary>
    /// 客户端学生账号管理API
    /// </summary>
    public class AccountController : ApiController
    {
        // 返回json数据格式
        private static readonly JsonMediaTypeFormatter JSON_FORMATTER = new JsonMediaTypeFormatter();

        /// <summary>
        /// 客户端账号登陆验证
        /// </summary>
        [HttpPost]
        public HttpResponseMessage Login()
        {
            // 0：服务器内部异常
            // 1: 安全码不正确
            // 2：账号密码不正确  
            // 3：安卓客户端机器码不正确  
            // 4：成功，可登陆

            int flag = 0;
            try
            {
                string account = WebQueryHelper.QueryFormString("account");
                string psword = WebQueryHelper.QueryFormString("psword");
                string android_code = WebQueryHelper.QueryFormString("code");
                string key = WebQueryHelper.QueryFormString("key");

                if (SafeKeyHelper.VerifySafeKey(key))
                {
                    if (StudentManager.IsPswordMatch(account, psword))
                    {
                        // 安卓机器码为空，第一次登录，写入机器码
                        string db_andorid_code = StudentManager.GetAndoridCode(account);
                        if (db_andorid_code.Length == 0)
                        {
                            StudentManager.SetAndroidCode(account, android_code);
                            StudentManager.SetOnline(account, true);
                            flag = 4;
                        }
                        else
                        {
                            if (android_code == db_andorid_code)
                            {
                                StudentManager.SetOnline(account, true);
                                flag = 4;
                            }
                            else
                            {
                                flag = 3;
                            }
                        }
                    }
                    else
                    {
                        flag = 2;
                    }
                }
                else
                {
                    flag = 1;
                }

            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("客户端调用学生账号登陆接口失败", ex);
            }

            Dictionary<string, int> json = new Dictionary<string, int>() { { "state", flag } };
            return Request.CreateResponse(HttpStatusCode.OK, json, JSON_FORMATTER);
        }

        /// <summary>
        /// 学生注销，改变在线状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage Logout()
        {
            // 0：服务器内部异常
            // 1: 安全码不正确
            // 2：注销的账号不存在  
            // 3：注销成功

            int flag = 0;
            try
            {
                string account = WebQueryHelper.QueryFormString("account");
                string key = WebQueryHelper.QueryFormString("key");

                if (SafeKeyHelper.VerifySafeKey(key))
                {
                    if (StudentManager.IsAccountExsit(account))
                    {
                        if (StudentManager.SetOnline(account, false))
                        {
                            StudentManager.SetLastLoginTime(account, DateTime.Now);
                            flag = 3;
                        }
                    }
                    else
                    {
                        flag = 2;
                    }
                }
                else
                {
                    flag = 1;
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("客户端调用学生账号注销接口失败", ex);
            }
            Dictionary<string, int> json = new Dictionary<string, int>() { { "state", flag } };
            return Request.CreateResponse(HttpStatusCode.OK, json, JSON_FORMATTER);
        }

        // <summary>
        /// 根据学生客户端账号获取学生信息(姓名，电话号码，账号,上一次登录时间)
        /// </summary>
        [HttpGet]
        public HttpResponseMessage GetStudentInfo(string account, string key)
        {
            string name = string.Empty;
            string phone = string.Empty;
            string last_login_time = string.Empty;
            try
            {
                if (SafeKeyHelper.VerifySafeKey(key))
                {
                    name = StudentManager.GetName(account);
                    phone = StudentManager.GetPhone(account);

                    Nullable<DateTime> time = StudentManager.GetLastLoginTime(account);
                    if (time.HasValue)
                    {
                        last_login_time = time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
            }
            catch (Exception ex)
            {
                account = string.Empty;
                name = string.Empty;
                phone = string.Empty;
                last_login_time = string.Empty;
                LogHelper.WriteLogAsync("客户端调用获取学生账号信息接口失败", ex);
            }

            Dictionary<string, string> json = new Dictionary<string, string>()
            {
                {"account",account},
                {"name",name},
                {"phone",phone},
                {"last_login_time",last_login_time}
            };

            return Request.CreateResponse(HttpStatusCode.OK, json, JSON_FORMATTER);
        }

        /// <summary>
        /// 修改学生登陆密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStudentPsword()
        {
            // 0：服务器内部异常
            // 1: 安全码不正确
            // 2: 账号不存在
            // 3: 旧密码不正确
            // 4：密码修改成功

            int flag = 0;
            try
            {
                string key = WebQueryHelper.QueryFormString("key");
                string account = WebQueryHelper.QueryFormString("account");
                string old_psword = WebQueryHelper.QueryFormString("old");
                string new_psword = WebQueryHelper.QueryFormString("new");

                if (SafeKeyHelper.VerifySafeKey(key))
                {
                    if (StudentManager.IsAccountExsit(account))
                    {
                        if (StudentManager.IsPswordMatch(account, old_psword))
                        {
                            if (StudentManager.SetPsword(account, new_psword)) { flag = 4; }
                        }
                        else
                        {
                            flag = 3;
                        }
                    }
                    else
                    {
                        flag = 2;
                    }
                }
                else
                {
                    flag = 1;
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("客户端调用修改学生登陆密码接口失败", ex);
            }

            Dictionary<string, int> json = new Dictionary<string, int>() { { "state", flag } };
            return Request.CreateResponse(HttpStatusCode.OK, json, JSON_FORMATTER);
        }
    }
}